<template>
  <view>
    <video v-show="videoShow" :style="'width:' +mobileWidth*0.8+'px;height:' +mobileHeight*0.8+'px;margin-left: 10%;'"></video>
    <view class="bg-video" v-if="mediaStreamTrack">
      <view class="flex justify-center align-center face-mask">
      </view>
      <text class="flex justify-center align-center flex-center-face">请保持姿势不变，人脸在屏幕中央</text>
      <view class="flex justify-center flex-center" style="z-index: 5;">
        <button class="start-btn" @click="handlePhotographClick">人脸识别验证</button>
      </view>
    </view>
<!--    <button class="start-btn" @click="invokingCamera">重新拍照</button>-->
  </view>
</template>
<script>
export default {
  name: 'cameraComponent',
  data() {
    return {
      mobileWidth:null,//手机宽度
      mobileHeight:null,//手机高度
      mediaStreamTrack: null, // 关闭摄像头
      videoShow: true,
    };
  },
  mounted () {
    this.invokingCamera();
  },
  // 退出页面时发生关闭摄像头
  beforeDestroy(){
    this.handlePhotographCloseClick();
  },
  methods: {
    // 调用原生摄像头
    invokingCamera() {
      const that = this;
      // 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
      // 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先，如果有getUserMedia的话，就获得它
          const getUserMedia =
              navigator.getUserMedia ||
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia;
          // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
          if (!getUserMedia) {
            return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，为老的navigator.getUserMedia方法包裹一个Promise
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }

      // 获取手机系统信息，获取摄像头权限
      uni.getSystemInfo({
        success: function (res) {
          that.mobileHeight = res.windowHeight;
          that.mobileWidth = res.windowWidth;
          const constraints = {
            audio: false,
            video: {
              // 前置摄像头
              facingMode: "user",
              // // 手机端相当于高
              width: Math.max(res.windowWidth, res.windowHeight),
              // // 手机端相当于宽
              height: Math.min(res.windowWidth, res.windowHeight),
            },
          };

         navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
           that.mediaStreamTrack = stream;
           const video = document.querySelector("video");
           // 旧的浏览器可能没有srcObject
           if ("srcObject" in video) {
             video.srcObject = stream;
           } else {
             // 防止在新的浏览器里使用它，应为它已经不再支持了
             video.src = window.URL.createObjectURL(stream);
           }
           video.onloadedmetadata = function (e) {
             video.play();
             that.videoShow = true;
           };
         }).catch(function (err) {
           console.log(err.name + ": " + err.message);
         });
        },
      });
    },
    handlePhotographCloseClick() {
      if (this.mediaStreamTrack) {
        // 关闭摄像头
        this.mediaStreamTrack.getTracks().forEach(function (track) {
          track.stop();
        });
        this.mediaStreamTrack = null;
      }
    },
    // 开始拍摄
    handlePhotographClick() {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      const video = document.querySelector("video");
      canvas.width = Math.min(video.videoWidth, video.videoHeight);
      canvas.height = Math.max(video.videoWidth, video.videoHeight);
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      this.$nextTick(() => {
        const base64 = canvas.toDataURL("image/jpeg");
        this.$emit('setBase64Img', base64)
        // 关闭摄像机
        this.handlePhotographCloseClick();
        this.videoShow=false;
      });
    },
  },
};

</script>
<style lang="scss" scoped>
  /deep/ .uni-video-container {
    background-color: transparent;
  }
	.start-btn{
		height: 90rpx;
		width: 350rpx;
		margin-top: 100rpx;
		background:$uni-color-primary;
		color:#fff
	}

/*人脸蒙层占位图*/
.face-mask {
  position: absolute;
  top: 35%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600rpx;
  height: 600rpx;
  border-radius: 80%;
  box-shadow: 0 0 0 9999px rgb(255, 255, 255);
}
/*点击人脸识别  绝对定位*/
.flex-center{
  width: 100vw;
  height: 36vh;
  position: absolute;
  bottom: 50px;
  left: 0;
  z-index: 2;
  overflow-y: hidden;
}

/*（请保持人脸在屏幕中央）绝对定位*/
.flex-center-face{
  width: 100vw;
  height: 15vh;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  overflow-y: hidden;
}
.bg-video{
  width: 100vw;
  height: 100vh;
  background-color: transparent;
  opacity: 1;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  overflow-y: hidden;
}
video {
  transform: rotateY(180deg);
  -webkit-transform: rotateY(180deg);
  /* Safari 和 Chrome */
  -moz-transform: rotateY(180deg);
}

::v-deep .uni-video-bar {
  display: none;
}

::v-deep .uni-video-cover {
  display: none;
}

</style>

